package com.cn.data.thread.future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author: chenl
 * @Date: 2019/4/3 0:00
 */
public class FutureTaskDemo {

    private ExecutorService executorService = Executors.newCachedThreadPool();

    private volatile int num = 0;

    public FutureTask<Integer> futureTask(int i){
        return new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName() + " num : " + i);
                return i;
            }
        });

    }

    public void testFuture() throws ExecutionException, InterruptedException {

        List<FutureTask<Integer>> futureTasks = new ArrayList<>();
        for (int i = 0 ; i < 10; i++ ){
            FutureTask<Integer> futureTask = futureTask(i);
            futureTasks.add(futureTask);
            executorService.submit(futureTask);
        }

        for (FutureTask<Integer> element : futureTasks){
            System.out.println("返回值：" + element.get().toString());
        }

        executorService.shutdown();

    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTaskDemo demo = new FutureTaskDemo();
        demo.testFuture();
    }
}
